﻿using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;
using LitJson;
using UnityEngine.UI;
using System.Threading;

public class test : MonoBehaviour
{
    public InputField input;

    private Socket tcp_ClientSocket;

    public Text txt;

    private string message = "";

    // Use this for initialization
    void Start()
    {

        tcp_ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


        tcp_ClientSocket.Connect(IPAddress.Parse("119.29.154.182"),6688);

        Debug.LogError("=连接成功=");

        new Thread(ReciveMessage).Start();
// 
//         string str = "hello world";
// 
//         byte[] data = new byte[1024];
// 
//         data = Encoding.UTF8.GetBytes(str);
// 
// 
//         tcp_ClientSocket.Send(data);
// 
//         byte[] data2 = new byte[1024];
// 
//         int lengh = tcp_ClientSocket.Receive(data2);
// 
// 
//         string str2 = Encoding.UTF8.GetString(data2, 0, lengh);
// 
//         Debug.LogError("=================" + str2);


// 
//         JSONClass jc = new JSONClass();
//         jc["name"] = "caojianlin";
//         jc["info"] = new JSONClass();
//         jc["info"]["age"] = "29";
//         jc["info"]["ge"] = "172";
// 
//         string str = jc.ToString();
// 
//         byte[] data = new byte[1024];
// 
//         data = Encoding.UTF8.GetBytes(str);
// 
//         
// 
//         tcp_ClientSocket.Send(data);
// 
//         byte[] data2 = new byte[1024];
// 
//         int lengh =  tcp_ClientSocket.Receive(data2);
// 
// 
//         string str2 = Encoding.UTF8.GetString(data2, 0, lengh);
// 
//         JSONNode jn = JSON.Parse(str2);
// 
//         Debug.LogError("============" + jn["aabc"]);

    }

    public void SendMessage()
    {
        byte[] data = new byte[1024];
      //  Debug.LogError("========" + input.text);
        data = Encoding.UTF8.GetBytes(input.text);
        tcp_ClientSocket.Send(data);
        
    }

    public void ReciveMessage()
    {
        while (true)
        {
            byte[] data = new byte[1024];
            int length = tcp_ClientSocket.Receive(data);
            message = Encoding.UTF8.GetString(data, 0, length);
            //Debug.LogError("=======" + str);
            //txt.text = "\n" + str;
        }
    }

    void OnDestroy()
    {
        tcp_ClientSocket.Shutdown(SocketShutdown.Both);
        tcp_ClientSocket.Close();
    }

    void Update()
    {

        if (message != null && message != "")
        {
            txt.text += "\n" + message;
            message = "";
        }
    }
}
